#python 3.8
import time
import hmac
import hashlib
import base64
import urllib.parse
import requests

import ssl

# from pkg.notice.notice_base import NoticeBase
# NoticeBase

print(ssl.OPENSSL_VERSION)

class lartNotice():
    """
    钉钉通知
    """
    def __init__(self, url, secret):
        self.url = url
        self.secret = secret

    def gen_sign(self, timestamp, secret):
        # 拼接timestamp和secret
        string_to_sign = '{}\n{}'.format(timestamp, secret)
        hmac_code = hmac.new(string_to_sign.encode("utf-8"), digestmod=hashlib.sha256).digest()
        # 对结果进行base64处理
        sign = base64.b64encode(hmac_code).decode('utf-8')
        return sign
    
    # 发送消息
    def send(self, msg):
        
        if self.secret:
            timestamp = str(round(time.time() * 1000))
            sign = self.gen_sign(timestamp, self.secret)
            url = self.url + '?timestamp=' + timestamp + '&sign=' + sign
        else :
            url = self.url
        
        headers = {
            'Content-Type': 'application/json'
        }
        data = {
            "msg_type": "text",     
            "content": {
                "text": msg
            }
        }
        response = requests.post(url, headers=headers, json=data)
        print(response.text)

if __name__ == '__main__':
    url = "https://open.feishu.cn/open-apis/bot/v2/hook/31657dac-e236-4613-978e-d0e6c079843f"
    secret = "12"
    ding = lartNotice(url, secret)
    ding.send("hello world")